package org.dioib.practice.controller;

import org.dioib.practice.common.Result;
import org.dioib.practice.common.constant.StatusCode;
import org.dioib.practice.model.SysUser;
import org.dioib.practice.service.ISysUserServicePlus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/plus/users")
public class SysUserControllerPlus {
    @Autowired
    private ISysUserServicePlus iSysUserServicePlus;

    /**
     * 创建用户，如果ID存在就修改用户，如果不存在就新建用户
     * @param sysUser 如果加上@RequestBody需要前端使用json格式的body传参
     * @return Result<T>
     */
    @PostMapping
    public Result<SysUser> createSysUser(SysUser sysUser){
        return iSysUserServicePlus.create(sysUser);
    }

    /**
     * 删除指定的ID数据
     * @param id
     * @return Result
     */
    @DeleteMapping("/{id}")
    public Result<SysUser> delSysUser(@PathVariable Long id){
        return iSysUserServicePlus.delete(id);
    }

    /**
     * 根据id列表删除数据
     * @param ids
     * @return Result
     */
    @DeleteMapping("/list")
    public Result<SysUser> delSysUsers(@RequestParam List<Long> ids){
        return iSysUserServicePlus.removeByIds(ids) ? Result.success(): Result.error(StatusCode.INTERNAL_ERROR);
    }

    /**
     * 修改数据
     * @param sysUser
     * @return Result
     */
    @PutMapping
    public Result<SysUser> updateSysUser(@RequestBody SysUser sysUser){
        return iSysUserServicePlus.update(sysUser);
    }

    /**
     * 根据ID查找数据
     * @param id
     * @return Result
     */
    @GetMapping("/{id}")
    public Result<SysUser> getSysUser(Long id){
        return iSysUserServicePlus.read(id);
    }

    /**
     * 获取所有用户
     * @param sysUser
     * @return
     */
    @GetMapping
    public Result<List<SysUser>> getSysUsers(SysUser sysUser){
        return iSysUserServicePlus.reads(sysUser);
    }

    //TODO 插入或修改，有则修改，没有就插入


    //废弃
    @PostMapping("/add")
    public Result<SysUser> addSysUser(SysUser sysUser){
        // 判断用户是否已经存在
        if (iSysUserServicePlus.getById(sysUser.getId()) != null) {
            // 用户已经存在，更新删除标记
            sysUser.setStatus(1);
            iSysUserServicePlus.updateById(sysUser);
            sysUser.setStatus(0);
        }
        return iSysUserServicePlus.save(sysUser) ? Result.success(): Result.error(StatusCode.INTERNAL_ERROR);
    }

    //TODO 逻辑删除，先删后插

    /**
     * 逻辑删除
     * @param id
     * @return Result
     */
    @DeleteMapping("/logic/{id}")
    public Result<SysUser> delSysUserLogic(@PathVariable Long id){
        SysUser sysUser = iSysUserServicePlus.getById(id);
        if(sysUser != null) {
            sysUser.setStatus(1);
            if(!iSysUserServicePlus.updateById(sysUser)){
                return Result.success();
            }
        }
        return Result.error(StatusCode.INTERNAL_ERROR);
    }

}
